package com.yao.service.impl;

import com.yao.dto.OrderDTO;
import com.yao.enums.ResultEnum;
import com.yao.exception.WeixinSellException;
import com.yao.service.BuyerService;
import com.yao.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * User: 姚宏武
 * Date: 2017/11/20
 * Time: 17:13
 * Email：401369870@qq.com
 * Description: 买家service实现
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {

        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) {
            log.error("【查询订单】订单不存在");
            throw new WeixinSellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    /**
     * 检查订单的所有者
     * @param openid 用户微信openid
     * @param orderId 订单id
     * @return
     */
    private OrderDTO checkOrderOwner(String openid, String orderId){
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }
        // 判断是否是自己的订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】与订单的openid不一致，openid={}，orderDTO={}",openid,orderDTO);
            throw new WeixinSellException(ResultEnum.ORDER_OWNER_ERROR);
        }

        return orderDTO;
    }


}
